//
//  VOLHireViewController.m
//  Volver
//
//  Created by administrator on 14-9-15.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLHireViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "REFrostedViewController.h"
#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"

#import "VOLAppDelegate.h"
#import "VOLHireCell.h"
#import "VOLHireCellModel.h"
#import "VOLHireAllInfoViewController.h"


@interface VOLHireViewController ()
{
    VOLAppDelegate *del;
    JSONDecoder *jd;
    NSFileManager *manager;
    MBProgressHUD *HUD;
    
    NSDateFormatter *formatter;
    
    double currentTime;
    //用来保存数据源的数组
    NSMutableArray *orderFormData;
    //保存未入住订单的数组
    NSMutableArray *failureData;
}

- (IBAction)goToInbox:(id)sender;

@end

@implementation VOLHireViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //初始化一些对象
    del = kGetDel;
    jd = [[JSONDecoder alloc] init];
    manager = [NSFileManager defaultManager];
    //初始化即将到来房客数据数组
    orderFormData = [NSMutableArray array];
    //初始化未入住的订单数据数组
    failureData = [NSMutableArray array];
    
    //添加标题
    self.title = @"出租主页";
    
    //添加菜单按钮,实现showMenu:方法
    addLeftNavigationBarButton();
    
    //添加编辑按钮，当有“未入住”订单时可以点按
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(edit:)];
    self.navigationItem.rightBarButtonItem.tintColor = kThemeColor;
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    //开启多行编辑功能
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
    
    //将noticeLabel隐藏，当需要显示时再显示出来
    self.noticeLabel.hidden = YES;
    
    //添加上拉下拉；
    [self setupRefresh];
    
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 进入界面时刷新
-(void)viewWillAppear:(BOOL)animated{
    if (del.isRefresh == 0) {//当不是从菜单栏或者发布成功时跳转过来的不用刷新
        return;
    }
    
    if (del.isRefresh == 5) {
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        [HUD showAnimated:YES whileExecutingBlock:^{
            //将是否刷新再置为0
            del.isRefresh = 0;
            [self loadHireData];
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
        }];
    }
    else{
        //将是否刷新置0
        del.isRefresh = 0;
        //开始刷新
        [self.tableView headerBeginRefreshing];
    }
    
    
}
#pragma mark - 其它方法
#pragma mark - 设置上拉、下拉
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(hireHeaderRereshing)];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    //    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"拼命加载中...";
    
//    self.tableView.footerPullToRefreshText = @"上拉加载更多数据";
//    self.tableView.footerReleaseToRefreshText = @"松开马上加载";
//    self.tableView.footerRefreshingText = @"拼命加载中...";
}

#pragma mark - 下拉刷新时调用的方法
-(void)hireHeaderRereshing{
    //加载数据，用异步方式
    [self loadHireData];
    
}




#pragma mark - 加载数据
#pragma mark 加载cell上的数据
-(void)loadHireData{
    //使用异步请求加载
    
    //发送异步请求
    
    //获取当前时间并转化为double
    NSString *nowStr = [formatter stringFromDate:[NSDate date]];
    NSDate *currentDate = [formatter dateFromString:nowStr];
    currentTime = [currentDate timeIntervalSince1970];
    
    double sevenDays = currentTime + kOneDaySeconds * 7;
//    double temp = currentTime;
    NSString *urlstr = [NSString stringWithFormat:@"%@orderform/searchWillComeInfo?userID=%d&sevenDays=%f&currentTime=%f",kHTTPHome,del.currentUser.userID,sevenDays,currentTime];
//    NSLog(@"temp = %@",[formatter stringFromDate:kTransformToDate(temp)]);
//    NSLog(@"sevenDays = %@",[formatter stringFromDate:kTransformToDate(sevenDays)]);
//    NSLog(@"currentTime = %f",kGetCurrentTime);

    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    //设置代理
    request.delegate = self;
    [request startAsynchronous];
}

#pragma mark 加载图片
-(void)loadImage:(NSString *)imageName houseID:(int)houseID indexPath:(NSIndexPath *)indexPath imagePath:(NSString *)imagePath{
    
    //开启新线程加载图片
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //组装image的url
        NSString *urlstr = [NSString stringWithFormat:@"%@%d/%@",kHouseImageHome,houseID,imageName];
        NSURL *url = [NSURL URLWithString:urlstr];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        if (image !=nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                VOLHireCell *cell = (VOLHireCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                cell.houseImageView.image = image;
                //本地保存图片
                [data writeToFile:imagePath atomically:YES];
            });
        }
        else{
            NSLog(@"没有图片");
        }
    });
    
}



#pragma mark - 按钮动作
#pragma mark 菜单按钮的动作
- (void)showMenu:(id)sender {
    kActionOfMenuButton;
}

#pragma mark 跳转到收件箱
- (IBAction)goToInbox:(id)sender {
    NSLog(@"消息");
}

#pragma mark 编辑按钮
-(void)edit:(id)sender{
    BOOL isEditing = !self.tableView.editing;
    if (isEditing) {
        [self.tableView setEditing:isEditing animated:YES];
        self.navigationItem.rightBarButtonItem.title = @"删除";
    }else{
        
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        [HUD showAnimated:YES whileExecutingBlock:^{
            [self deleteOrderForm];
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
        }];
        
        
        self.navigationItem.rightBarButtonItem.title = @"编辑";
        [self.tableView setEditing:isEditing animated:YES];
    }
}

#pragma mark 删除订单操作
-(void)deleteOrderForm{
    //获取被选中的cell的indexPath，
    NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];
    if (selectedRows.count == 0) {
        return;
    }
    
    //创建数组，将删除成功的indexPath加入其中，删除cell时用到
    NSMutableArray *deletedArray = [NSMutableArray array];
    
    //创建一个堆，将删除成功的indexPath.row加入其中，删除historyData中的数据时用到
    NSMutableIndexSet *deletedSet = [NSMutableIndexSet new];
    
    //遍历数组删除数据
    for (NSIndexPath *indexPath in selectedRows) {
        VOLHireCellModel *model = orderFormData[indexPath.row];
        
        //连接网络删除订单表中的内容
//        int isDelete = [self deleteFavoriteFormTable:model.houseID];
        int isDelete = [self deleteOrderFormFormTable:model.orderFormID];
        
        if (isDelete) {//删除成功
            //将indexPath加入到deletedArray中
            [deletedArray addObject:indexPath];
            //将indexPath.row加入到deletedSet中
            [deletedSet addIndex:indexPath.row];
            //将failureData中的
            [failureData removeObject:model];
        }
        
    }
    
    if (deletedArray.count == 0) {
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //遍历结束时删除对应的数据和cell
        //先删除数据
        [orderFormData removeObjectsAtIndexes:deletedSet];
        //再删除cell
        [self.tableView deleteRowsAtIndexPaths:deletedArray withRowAnimation:UITableViewRowAnimationAutomatic];
        
        
        //删除完之后如果failureData为空，要将编辑按钮失效
        if (failureData.count == 0) {
            self.navigationItem.rightBarButtonItem.enabled = NO;
        }
    });
    
    
}

#pragma mark 连网删除订单表中的内容
-(int)deleteOrderFormFormTable:(int)orderFormID{
    
    NSString *urlstr = [NSString stringWithFormat:@"%@orderform/deleteOrderForm?orderFormID=%d",kHTTPHome,orderFormID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    if (data) {
        NSDictionary *dic = [jd objectWithData:data];
        int result = [[dic objectForKey:@"result"] intValue];
        return result;
    }else{
        NSLog(@"deleteOrderFormFormTable------data为空");
        return 0;
    }
}

#pragma mark - 代理方法

#pragma mark - 异步请求代理
#pragma mark 请求成功
-(void)requestFinished:(ASIHTTPRequest *)request{
    //得到返回数据
    NSData *data = [request responseData];
    if (data == nil) {
        NSLog(@"hire------data为空");
        return;
    }
    
    
    NSDictionary *dic = [jd objectWithData:data];
    int result = [[dic objectForKey:@"result"] intValue];
    if (result == 0) {
        NSLog(@"hire-----查询失败,result = 0");
        [orderFormData removeAllObjects];
//        return;
    }
    else{
        //首先判断myJourneyData是否为空，如果不是，先清空
        if (orderFormData.count != 0) {
            [orderFormData removeAllObjects];
        }
        if (failureData.count != 0) {
            [failureData removeAllObjects];
        }
        
        //得到订单数组
        NSArray *array = [dic objectForKey:@"information"];
        
        //遍历这个数组
        for (NSDictionary *obj in array) {
            VOLHireCellModel *model = [[VOLHireCellModel alloc] init];
            
            model.orderFormID = [[obj objectForKey:@"of_id"] intValue];
            model.houseID = [[obj objectForKey:@"house_id"] intValue];
            model.houseTitle = [obj objectForKey:@"house_title"];
            model.userID = [[obj objectForKey:@"user_id"] intValue];
            model.userName = [obj objectForKey:@"user_name"];
            model.status = [[obj objectForKey:@"status"] intValue];
            model.arriveDate = [[obj objectForKey:@"arrive_date"] doubleValue];
            model.leaveDate = [[obj objectForKey:@"leave_date"] doubleValue];
            model.houseImageName = [obj objectForKey:@"image_name"];
            
            if (model.arriveDate < currentTime && model.status == 0) {
                [failureData addObject:model];
            }
            
            //将model加入到orderFormData
            [orderFormData addObject:model];
        }
    }
    
    
    //数组遍历完毕，更新主界面
    //判断是否有即将到来或离开的房客
    if (orderFormData.count == 0) {
        //提示label
        self.noticeLabel.text = @"显示未来七天内即将到达的游客";
        self.noticeLabel.textColor = kThemeColor;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.noticeLabel.hidden = NO;
    }else{
        //初始化formatter
//        formatter = [[NSDateFormatter alloc] init];
//        [formatter setDateFormat:@"yyyy年MM月dd日"];
        self.noticeLabel.hidden = YES;
    }
    
    //如果有未入住的房客，编辑按钮有效
    if (failureData.count != 0) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }

    
    //刷新tableView
    [self.tableView reloadData];
    
    //停止刷新动作
    [self.tableView headerEndRefreshing];
    
}


#pragma mark 请求失败
-(void)requestFailed:(ASIHTTPRequest *)request{
    //停止刷新动作
    [self.tableView headerEndRefreshing];
    NSLog(@"hire-----请求失败");
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return orderFormData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"hireCell";
    VOLHireCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    
    VOLHireCellModel *model = orderFormData[indexPath.row];
    cell.houseTitleLabel.text = model.houseTitle;
    cell.guestNameLabel.text = [NSString stringWithFormat:@"房客：%@",model.userName];
    NSString *arriveStr = [formatter stringFromDate:kTransformToDate(model.arriveDate)];
    cell.arriveDateLabel.text = [NSString stringWithFormat:@"%@",arriveStr];
    NSString *leaveStr = [formatter stringFromDate:kTransformToDate(model.leaveDate)];
    cell.leaveDateLabel.text = [NSString stringWithFormat:@"%@",leaveStr];
    
    //设置状态Label
    if (model.arriveDate >= currentTime) {
        if (model.status && model.arriveDate == currentTime) {
            cell.statusLabel.text = @"已入住";
            cell.statusLabel.textColor = [UIColor lightGrayColor];
            
            cell.arriveDateLabel.textColor = [UIColor lightGrayColor];
            cell.leaveDateLabel.textColor = [UIColor lightGrayColor];
        }else{
            cell.statusLabel.text = @"即将入住";
            cell.statusLabel.textColor = kThemeColor;
            
            cell.arriveDateLabel.textColor = kThemeColor;
            cell.leaveDateLabel.textColor = kThemeColor;
        }
    }else if (model.leaveDate >= currentTime){
        if (model.status == 1) {
            cell.statusLabel.text = @"即将离开";
            cell.statusLabel.textColor = [UIColor redColor];
            
            cell.arriveDateLabel.textColor = kThemeColor;
            cell.leaveDateLabel.textColor = kThemeColor;
        }
        if (model.arriveDate < currentTime && model.status == 0) {
            cell.statusLabel.text = @"未入住";
            cell.statusLabel.textColor = kOrangeColor;
            
            cell.arriveDateLabel.textColor = kOrangeColor;
            cell.leaveDateLabel.textColor = kOrangeColor;
        }
        
    }
    
    //加载图片
    //先判断是否有这个路径存在，如果没有要先创建
    NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/houseImages/%d",kGetDocumentsPath,del.currentUser.userID,model.houseID];
    if (![manager fileExistsAtPath:imageDocumentPath]) {
        [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //先从本地查找是否已有图片
    NSString *imagePath = [NSString stringWithFormat:@"%@%d/houseImages/%d/%@",kGetDocumentsPath,del.currentUser.userID,model.houseID,model.houseImageName];
    if ([manager fileExistsAtPath:imagePath]) {
        cell.houseImageView.image = [UIImage imageWithContentsOfFile:imagePath];
    }
    else{
        //若不存在，调用方法下载图片
        [self loadImage:model.houseImageName houseID:model.houseID indexPath:indexPath imagePath:imagePath];
    }
    
    return cell;
}

#pragma mark 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105;
}

#pragma mark 点击某一行cell时
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableView.editing) {
        if (![failureData containsObject:orderFormData[indexPath.row]]) {
            [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        }
        
        return;
    }
    
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    VOLHireAllInfoViewController *hireAllInfo = [self.storyboard instantiateViewControllerWithIdentifier:@"hireAllInfoController"];
    hireAllInfo.orderFormID = [orderFormData[indexPath.row] orderFormID];
    [self.navigationController pushViewController:hireAllInfo animated:YES];
}

@end
